using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Management;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace BizTalk.BuildGenerator.Tasks
{
    /// <summary>
    /// Task to create a send handler
    /// </summary>
    public class CreateReceiveHandler: Task
    {
        private string _AdapterName;
        private string _HostName;
        /// <summary>
        /// Host name
        /// </summary>
        [Required]
        public string HostName
        {
            get { return _HostName; }
            set { _HostName = value; }
        }
        /// <summary>
        /// Adapter name
        /// </summary>
        [Required]
        public string AdapterName
        {
            get { return _AdapterName; }
            set { _AdapterName = value; }
        }

        /// <summary>
        /// The execute method
        /// </summary>
        /// <returns></returns>
        public override bool  Execute()
        {
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                using (ManagementClass recieveHandlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ReceiveHandler", null))
                {
                    foreach (ManagementObject recieveHandler in recieveHandlerManagementClass.GetInstances())
                    {
                        if ((string)recieveHandler["AdapterName"] == this._AdapterName
                            && (string)recieveHandler["HostName"] == this._HostName)
                        {
                            recieveHandler.Delete();
                        }
                    }

                    using (ManagementObject recieveHandlerManager = recieveHandlerManagementClass.CreateInstance())
                    {
                        recieveHandlerManager["AdapterName"] = this._AdapterName;
                        recieveHandlerManager["HostName"] = this._HostName;
                        recieveHandlerManager.Put(options);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(this.GetType().FullName, ex.ToString());
                throw;
            }
        }       
    }
}
